package com.jianjian.system.controller;

import com.jianjian.common.result.Result;
import com.jianjian.common.utils.JwtHelper;
import com.jianjian.common.utils.MD5;
import com.jianjian.model.system.SysUser;
import com.jianjian.model.vo.LoginVo;
import com.jianjian.system.handler.GuiGuException;
import com.jianjian.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Zsir
 * @create 2022-10-31 15:03
 */
@Api("用户登录接口")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private SysUserService sysUserService;

    //Login
    @ApiOperation(value = "登录接口")
    @PostMapping("login")
    public Result login(@RequestBody(required = true) LoginVo loginVo){

        //根据username查询用户
       SysUser sysUser =  sysUserService.getUserByUsername(loginVo.getUsername());

       //判断用户对象是否为空
        if (sysUser == null){
            throw new GuiGuException(502,"该用户不存在");
        }
        //判断密码是否存在
        if (!sysUser.getPassword().equals(MD5.encrypt(loginVo.getPassword()))){
            throw new GuiGuException(502,"密码错误");
        }
        //判断是否可用status
        if (sysUser.getStatus() == 0){
            throw new GuiGuException(502,"该用户不可用");
        }

        //根据userId和username返回token
        String token = JwtHelper.createToken(Long.parseLong(sysUser.getId()), sysUser.getUsername());

        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        return Result.ok(map);
    }

    //Info
    @ApiOperation(value = "登录响应数据接口")
    @GetMapping("info")
    public Result info(HttpServletRequest request){
    //获取请求头中的token值
        String token = request.getHeader("token");
    //根据token字符串获取用户名称
        String username = JwtHelper.getUsername(token);
    //根据用户名称获取用户信息（基本信息 和 菜单权限 和 按钮权限）
        Map<String, Object> map =  sysUserService.getUserInfo(username);

        return Result.ok(map);
    }

}
